<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2//EN">
<html><head><title>Programming in Lua : 3.6</title>
<link rel="stylesheet" type="text/css" href="pil.css">
</head>
<body>
<p class="warning">
<A HREF="contents.html"><IMG TITLE="Programming in Lua (first edition)" SRC="capa.jpg" ALT="" ALIGN="left"></A>This first edition was written for Lua 5.0. While still largely relevant for later versions, there are some differences.<BR>The third edition targets Lua 5.2 and is available at <A HREF="http://www.amazon.com/exec/obidos/ASIN/859037985X/theprogrammil3-20">Amazon</A> and other bookstores.<BR>By buying the book, you also help to <A HREF="../donations.html">support the Lua project</A>.
</p>
<table width="100%" class="nav">
<tr>
<td width="10%" align="left"><a href="3.5.html"><img border="0" src="left.png" alt="Previous"></a></td>
<td width="80%" align="center"><a href="contents.html"><font face="Helvetica,Arial,sanserif">
<font color="gray">Programming in </font><font color="blue"> Lua</font>
</font></a></td>
<td width="10%" align="right"><a href="4.html"><img border="0" src="right.png" alt="Next"></a></td>
</tr>
<tr>
<td width="10%" align="left"></td>
<td width="80%" align="center"><a href="contents.html#P1">Part I. The Language</a>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
<a href="contents.html#3">Chapter 3. Expressions</a></td>
<td width="10%" align="right"></td></tr>
</table>
<hr/>
<p><a name="tableconstructor"><h2>3.6 &ndash; Table Constructors</h2></a>

<p>


<p>Constructors are expressions that create and
initialize tables.
They are a distinctive feature of Lua
and one of its most useful and versatile mechanisms.

<p>The simplest constructor is the empty constructor,
<code>{}</code>, which creates an empty table;
we saw it before.
Constructors also initialize arrays
(called also <em>sequences</em> or <em>lists</em>).
For instance, the statement
<pre>
    days = {"Sunday", "Monday", "Tuesday", "Wednesday",
            "Thursday", "Friday", "Saturday"}
</pre>
will initialize <code>days[1]</code> with the string <code>"Sunday"</code>
(the first element has always index 1, not 0),
<code>days[2]</code> with <code>"Monday"</code>,
and so on:
<pre>
    print(days[4])  --> Wednesday
</pre>

<p>Constructors do not need to use only constant expressions.
We can use any kind of expression for the value of each element.
For instance, we can build a short sine table as
<pre>
    tab = {sin(1), sin(2), sin(3), sin(4),
           sin(5), sin(6), sin(7), sin(8)}
</pre>

<p>To initialize a table to be used as a record,
Lua offers the following syntax:
<pre>
    a = {x=0, y=0}
</pre>
which is equivalent to
<pre>
    a = {}; a.x=0; a.y=0
</pre>

<p>No matter what constructor we use to create a table,
we can always add and remove other fields of any type to it:
<pre>
    w = {x=0, y=0, label="console"}
    x = {sin(0), sin(1), sin(2)}
    w[1] = "another field"
    x.f = w
    print(w["x"])   --> 0
    print(w[1])     --> another field
    print(x.f[1])   --> another field
    w.x = nil       -- remove field "x"
</pre>
That is, <em>all tables are created equal</em>;
constructors only affect their initialization.

<p>Every time Lua evaluates a constructor,
it creates and initializes a new table.
Consequently, we can use tables to implement linked lists:
<pre>
    list = nil
    for line in io.lines() do
      list = {next=list, value=line}
    end
</pre>
This code reads lines from the standard input
and stores them in a linked list, in reverse order.
Each node in the list is a table with two fields:
<code>value</code>, with the line contents,
and <code>next</code>, with a reference to the next node.
The following code prints the list contents:
<pre>
    l = list
    while l do
      print(l.value)
      l = l.next
    end
</pre>
(Because we implemented our list as a stack,
the lines will be printed in reverse order.)
Although instructive,
we hardly use the above implementation in real Lua programs;
lists are better implemented as arrays,
as we will see in <a href="11.html#DataStructure">Chapter 11</a>.

<p>We can mix record-style and list-style
initializations in the same constructor:
<pre>
    polyline = {color="blue", thickness=2, npoints=4,
                 {x=0,   y=0},
                 {x=-10, y=0},
                 {x=-10, y=1},
                 {x=0,   y=1}
               }
</pre>
The above example also illustrates how we can nest constructors
to represent more complex data structures.
Each of the elements <code>polyline[1]</code>, ..., <code>polyline[4]</code>
is a table representing a record:
<pre>
    print(polyline[2].x)    --> -10
</pre>

<p>Those two constructor forms have their limitations.
For instance,
you cannot initialize fields with negative indices,
or with string indices that are not proper identifiers.
For such needs, there is another, more general, format.
In this format,
we explicitly write the index to be initialized as an expression,
between square brackets:
<pre>
    opnames = {["+"] = "add", ["-"] = "sub",
               ["*"] = "mul", ["/"] = "div"}
    
    i = 20; s = "-"
    a = {[i+0] = s, [i+1] = s..s, [i+2] = s..s..s}
    
    print(opnames[s])    --> sub
    print(a[22])         --> ---
</pre>
That syntax is more cumbersome, but more flexible too:
Both the list-style and the record-style forms are special
cases of this more general one.
The constructor
<pre>
    {x=0, y=0}
</pre>
is equivalent to
<pre>
    {["x"]=0, ["y"]=0}
</pre>
and the constructor
<pre>
    {"red", "green", "blue"}
</pre>
is equivalent to
<pre>
    {[1]="red", [2]="green", [3]="blue"}
</pre>

<p>For those that really want their arrays starting at 0,
it is not difficult to write the following:
<pre>
    days = {[0]="Sunday", "Monday", "Tuesday", "Wednesday",
            "Thursday", "Friday", "Saturday"}
</pre>
Now, the first value, <code>"Sunday"</code>, is at index 0.
That zero does not affect the other fields,
but <code>"Monday"</code> naturally goes to index 1,
because it is the first list value in the constructor;
the other values follow it.
Despite this facility,
I do not recommend the use of arrays starting at 0 in Lua.
Remember that most functions assume that
arrays start at index 1,
and therefore will not handle such arrays correctly.

<p>You can always put a comma after the last entry.
These trailing commas are optional, but are always valid:
<pre>
    a = {[1]="red", [2]="green", [3]="blue",}
</pre>
Such flexibility makes it easier to write programs that generate Lua tables,
because they do not need to handle the last element as a special case.

<p>Finally, you can always use a semicolon instead of a comma in a constructor.
We usually reserve semicolons to delimit
different sections in a constructor,
for instance to separate its list part from its record part:
<pre>
    {x=10, y=45; "one", "two", "three"}
</pre>

<p>
<hr/>
<table width="100%" class="nav">
<tr valign="top">
<td width="90%" align="left">
<small>
  Copyright &copy; 2003&ndash;2004 Roberto Ierusalimschy.  All rights reserved.
</small>
</td>
<td width="10%" align="right"><a href="4.html"><img border="0" src="right.png" alt="Next"></a></td>
</tr>
</table>


</body></html>

